﻿using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;

namespace DotNetty.Extensions
{
    class TcpClientHandler : SimpleChannelInboundHandler<object>
    {
        private readonly TcpSocketClient _client;

        public TcpClientHandler(TcpSocketClient client)
        {
            _client = client;
        }

        //public override void ChannelActive(IChannelHandlerContext context)
        //{
        //    _client.Connected(context.Channel);
        //}

        protected override void ChannelRead0(IChannelHandlerContext context, object msg)
        {
            _client.Message(msg);
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
            _client.Ex(exception);
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            _client.Disconnected();
        }

        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt is IdleStateEvent eventState)
            {
                if (eventState != null)
                {
                    context.Channel.CloseAsync();
                }
            }
        }

    }
}
